package com.sca.bussiness.utils;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @author liuxianfei
 * @since 2020/11/11 14:09
 */
public class TraceUtil {

    private static final String TRACE_ID = "TraceId";

    /**
     * 为请求分配一个traceId
     *
     * @param request
     */
    public static String assignRequestTraceId(HttpServletRequest request) {
        String traceId = GuidGenerator.generate();
        request.setAttribute(TRACE_ID, traceId);
        return traceId;
    }

    /**
     * 获取一个请求的traceId.
     *
     * @param request
     * @return
     */
    public static String getRequestTraceId(HttpServletRequest request) {
        return (String) request.getAttribute(TRACE_ID);
    }

    /**
     * 获取当前线程的request对应的traceId
     *
     * @return
     */
    public static String getCurrentRequestTraceId() {
        return getRequestTraceId(((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest());
    }


}
